package events

import (
	"github.com/jinzhu/gorm"
	"meman/sys/basic"
)

const (
	TABLE_SUBSCRIBERS = "subscribers"
)

/**
订阅者
 */
type Subscriber struct {
	SubscriberId int `gorm:"primary_key;AUTO_INCREMENT;column:subscriber_id"`
	SubscriberName string `gorm:"column:subscriber_name"`
	SubscriberKey string `gorm:"column:subscriber_key"`
	SecretKey string  `gorm:"column:secret_key"`
	Comment string  `gorm:"column:comment"`
	RegisterTime int64 `gorm:"column:register_time"`
	Status int  `gorm:"column:status"`
	AllowedMessageClassToSend string  `gorm:"column:allowed_message_class_to_send"`
	EmailAddress string  `gorm:"column:email_address"`
	Privileges string  `gorm:"column:privileges"`
}
/**
gin使用checkbox获取值失败,需要自己定义一个struct 进行转
 */
type Privileges struct {
	Privileges []string `form:"privileges[]"`
}
type AllowedMessageClassToSend struct {
	Messages []string `form:"allowed_message_class_to_send[]"`
}

/**
获取订阅者列表
@return []Subscriber, error  返回订阅者列表,错误信息
 */
func (s *Subscriber) GetNames() ([]Subscriber, error)   {
	db := basic.Write()
	var subscribers []Subscriber
	err := db.Table(TABLE_SUBSCRIBERS).Select("subscriber_name, subscriber_id, subscriber_key").Order("subscriber_name").Find(&subscribers).Error
	return subscribers, err
}
/**
按条件获取订阅者信息.
 */
func (s *Subscriber) GetListByCond(conds map[string]interface{}) ([]Subscriber, error)  {
	db := basic.Write()
	var subscribers []Subscriber
	err := db.Table(TABLE_SUBSCRIBERS).Where(conds).Find(&subscribers).Error
	return subscribers, err

}


/**
获取订阅者列表
@param conds map[string]interface{} where语句参数,查询条件.
@param page int  当前页码
@param pageSize int  每页有几个数据
@return []Message,count  返回订阅者列表,错误
 */
func (s *Subscriber) GetList(db *gorm.DB,conds map[string]interface{}, page, perPageNums int) ([]Subscriber, error){
	start := GetPageStart(page, perPageNums)
	var subscribers []Subscriber
	err := db.Table(TABLE_SUBSCRIBERS).Where(conds).Limit(perPageNums).Offset(start).Find(&subscribers).Error
	return subscribers, err
}




/**
插入一条数据
 */
func(s *Subscriber) Insert() error {
	db := basic.Write()
	err := db.Table(TABLE_SUBSCRIBERS).Save(&s).Error
	return err
}

/**
根据id查找数据
 */
func(s *Subscriber) FindById(id int) (Subscriber, error) {
	db := basic.Read()
	var subscriber Subscriber
	err := db.Table(TABLE_SUBSCRIBERS).Where("subscriber_id = ?", id).First(&subscriber).Error
	return subscriber, err
}

/**
更新
 */
func(m *Subscriber) Update(id int,conds map[string]interface{}) error {
	db := basic.Write()
	err := db.Table(TABLE_SUBSCRIBERS).Where("subscriber_id = ?", id).Updates(conds).Error
	return err
}

/**
删除, 根据id 删除数据
 */
func(s *Subscriber) DeleteById(id int) error {
	db := basic.Write()
	err := db.Table(TABLE_SUBSCRIBERS).Where("subscriber_id = ?", id).Delete(&s).Error
	return err
}
